package com.zyf.baselibrary.base

import android.Manifest
import android.content.ComponentName
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.WindowInsets
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.baselibrary.bases.Constants.MEDATIONID
import com.example.baselibrary.utlis.ActivityCollector
import com.example.baselibrary.utlis.AppCache
import com.example.baselibrary.utlis.AppInfoUtil
import com.example.baselibrary.utlis.ContextUtils
import com.example.baselibrary.utlis.LogUtils
import com.example.baselibrary.utlis.PermissionInterceptor
import com.example.baselibrary.utlis.RebootReceiverManager
import com.example.baselibrary.utlis.RestartHelper
import com.example.baselibrary.wigits.XLoadingDialogManger
import com.hjq.permissions.XXPermissions
import com.xuexiang.xui.XUI
import com.xuexiang.xui.utils.XToastUtils
import com.zyf.base.event.EventTimeClock
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.ref.WeakReference


/**
 * 基础Activity类，提供通用功能封装
 *
 * @author 郑
 * @date 2024/8/27.
 * @version 1.1
 */
abstract class BaseActivity : AppCompatActivity() {
    val mAcache = AppCache.get()
    // ==================== 生命周期管理 ====================
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        initDependencies()
        checkEssentialPermissions()
        RebootReceiverManager.getInstance(this).registerRebootReceiver()

        // 检查并请求必要权限
        if (isChineseROM()) {
            requestAutoStartPermission()
        }
    }

    private fun isChineseROM(): Boolean {
        return Build.MANUFACTURER.lowercase() in setOf("xiaomi", "huawei", "oppo", "vivo")
    }

    private fun requestAutoStartPermission() {
        try {
            val intent = Intent()
            when (Build.MANUFACTURER.lowercase()) {
                "xiaomi" -> intent.component = ComponentName(
                    "com.miui.securitycenter",
                    "com.miui.permcenter.autostart.AutoStartManagementActivity"
                )

                "huawei" -> intent.component = ComponentName(
                    "com.huawei.systemmanager",
                    "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity"
                )
                // 其他厂商...
            }
            startActivity(intent)
        } catch (e: Exception) {
            Toast.makeText(this, "请手动在设置中允许应用自启动", Toast.LENGTH_LONG).show()
        }
    }

    override fun onPostCreate(savedInstanceState: Bundle?) {
        super.onPostCreate(savedInstanceState)
        initViews()
        initData()
        initListeners()
        ActivityCollector.addActivity(this)
    }

    override fun onResume() {
        super.onResume()
        // 取消可能存在的重启计划
        RestartHelper.cancelScheduledRestart(this)
    }

    override fun onPause() {
        super.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        cleanUpResources()
        RebootReceiverManager.getInstance(this).unregisterRebootReceiver()
        XLoadingDialogManger.getInstance().hideLoading()
        ActivityCollector.removeActivity(this)
    }

    // ==================== 初始化方法 ====================
    protected open fun initDependencies() {
        EventBus.getDefault().register(this)
    }

    protected open fun initViews() {}

    protected open fun initData() {}

    protected open fun initListeners() {}

    protected open fun cleanUpResources() {
        EventBus.getDefault().unregister(this)
    }

    //加载框显示和取消
    protected open fun showLoading() {
        XLoadingDialogManger.getInstance().showLoading(ContextUtils.getContextSafely() ?: this)
    }

    protected open fun cancelLoading() {
        XLoadingDialogManger.getInstance().hideLoading()
    }

    // ==================== 权限管理 ====================
    /**
     * 密封类定义权限组
     */
    sealed class PermissionGroup {
        object Basic : PermissionGroup()
        object Storage : PermissionGroup()
        object Camera : PermissionGroup()
        object Notification : PermissionGroup()

        fun getPermissions(targetSdkVersion: Int): Array<String> {
            return when (this) {
                Basic -> arrayOf(Manifest.permission.READ_PHONE_STATE)
                Storage -> getStoragePermissions(targetSdkVersion)
                Camera -> arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO)
                Notification -> arrayOf(Manifest.permission.POST_NOTIFICATIONS)
            }
        }

        private fun getStoragePermissions(targetSdkVersion: Int): Array<String> {
            return when {
                targetSdkVersion >= Build.VERSION_CODES.TIRAMISU -> {
                    arrayOf(
                        Manifest.permission.READ_MEDIA_IMAGES,
                        Manifest.permission.READ_MEDIA_VIDEO,
                        Manifest.permission.READ_MEDIA_AUDIO
                    )
                }

                Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q -> {
                    arrayOf(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    )
                }

                else -> {
                    arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
                }
            }
        }
    }


    /**
     * 获取应用必需的权限组
     */
    /**
     * 获取应用必需的权限组
     */
    protected open fun getEssentialPermissions(): Array<PermissionGroup> {
        val basePermissions = arrayOf(
            PermissionGroup.Basic,
            PermissionGroup.Storage,
            PermissionGroup.Camera
        )

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            basePermissions + PermissionGroup.Notification
        } else {
            basePermissions
        }
    }


    /**
     * 检查必需权限
     */
    private fun checkEssentialPermissions() {
        val allPermissions = getEssentialPermissions()
            .flatMap { it.getPermissions(applicationInfo.targetSdkVersion).toList() }
            .toTypedArray()

        checkPermissions(allPermissions)
    }


    /**
     * 权限检查
     */
    /**
     * 权限检查
     */
    protected open fun checkPermissions(permissions: Array<String>) {
        // 过滤掉已经授予的权限，提高效率
        val needRequestPermissions = permissions.filter {
            !XXPermissions.isGranted(this, it)
        }.toTypedArray()

        if (needRequestPermissions.isEmpty()) {
            onPermissionsGranted()
            return
        }

        XXPermissions.with(this)
            .permission(*needRequestPermissions)
            .interceptor(PermissionInterceptor())
            .request { _, allGranted ->
                if (allGranted) {
                    onPermissionsGranted()
                } else {
                    onPermissionsDenied()
                }
            }
    }


    protected open fun onPermissionsGranted() {
        // 默认实现，子类可覆盖
        cacheDeviceId()
    }

    protected open fun onPermissionsDenied() {
        XToastUtils.error("必要权限获取失败")
    }

    private fun cacheDeviceId() {
        //存储设备ID
        AppCache.get()?.put(MEDATIONID, AppInfoUtil.getSafeDeviceId(this))
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTimeEvent(timeType: EventTimeClock) {
//        when (timeType.type) {
//            TimeClockType.ONE_SECOND -> onOneSecond()
//            TimeClockType.FIVE_SECOND -> onFiveSeconds()
//            TimeClockType.TEN_SECOND -> onTenSeconds()
//            TimeClockType.HALF_MINUTE -> onHalfMinute()
//            TimeClockType.ONE_MINUTE -> onOneMinute()
//        }
    }

     fun addTouchFeedback(view: View) {
        // 使用弱引用避免内存泄漏
        val weakActivity = WeakReference(this)
        view.setOnTouchListener { v, event ->
            val activity = weakActivity.get()
            if (activity == null || activity.isFinishing || activity.isDestroyed) {
                return@setOnTouchListener false
            }

            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    v.alpha = 0.7f
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    v.alpha = 1.0f
                }
                MotionEvent.ACTION_MOVE -> {
                    val x = event.x
                    val y = event.y
                    if (x < 0 || x > v.width || y < 0 || y > v.height) {
                        v.alpha = 1.0f
                    }
                }
            }
            false
        }

        // 添加视图销毁时的清理逻辑
        view.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
            override fun onViewAttachedToWindow(v: View) {}

            override fun onViewDetachedFromWindow(v: View) {
                v.setOnTouchListener(null)
            }
        })
    }

    // ==================== 导航管理 ====================
    /**
     * 启动新Activity
     * @param clazz 目标Activity类
     * @param bundle 传递的数据Bundle
     * @param flags Intent标志
     */
    protected fun navigateTo(
        clazz: Class<*>,
        bundle: Bundle? = null,
        flags: Int = -1
    ) {
        Intent(this, clazz).apply {
            bundle?.let { putExtras(it) }
            if (flags != -1) {
                addFlags(flags)
            }
            startActivity(this)
        }
    }

    /**
     * 启动新Activity并关闭当前
     * @param clazz 目标Activity类
     * @param bundle 传递的数据Bundle
     */
    protected fun navigateToAndFinish(
        clazz: Class<*>,
        bundle: Bundle? = null
    ) {
        navigateTo(clazz, bundle)
        finish()
    }

    // ==================== 退出管理 ====================
    private var exitTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (ActivityCollector.isLastActivity() && keyCode == KeyEvent.KEYCODE_BACK) {
            handleExit()
            return false
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 处理退出逻辑
     */
    protected open fun handleExit() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            LogUtils.logEvent("再按一次退出程序")
            exitTime = System.currentTimeMillis()
        } else {
            exitApplication()
        }
    }

    /**
     * 退出应用
     */
    protected open fun exitApplication() {
        ActivityCollector.finishAll()
        stopAllServices()
        System.exit(0)
    }

    /**
     * 停止所有服务
     */
    protected open fun stopAllServices() {
        // 服务停止逻辑
    }

    // ==================== 异常处理 ====================
    /**
     * 全局异常处理
     */
    protected open fun handleException(e: Exception) {
        LogUtils.logEvent("Exception: ${e.message}")
        // 可添加上报逻辑
    }
}